package org.qiuqiu.backcontroller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

/*import org.apache.commons.io.FileUtils;*/
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.qiuqiu.service.UserService;
import org.qiuqiu.service.impl.PostServiceImpl;
import org.qiuqiu.service.impl.UserServiceImpl;
import org.qiuqiu.vo.PaginationVO;
import org.qiuqiu.vo.Post;
import org.qiuqiu.vo.PostExample;
import org.qiuqiu.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/***
 * 
 * @author wangsongmao
 *2015年1月30日
 * 下午2:29:40
 */
@Controller
@RequestMapping(value = "/back")
public class BackController {

	@Autowired
	private PostServiceImpl postServiceImpl;
	@Autowired
	private UserService impl;
	// 用来构建JsonGenerator对象
	private ObjectMapper objectMapper = new ObjectMapper();
	// 用来创建json数据
	private JsonGenerator jsonGenerator = null;

	@RequestMapping(value = "/postList", method = RequestMethod.POST)
	public void getAllPost(
			@RequestParam(required = false, value = "key") String key,
			HttpServletResponse rs,
			HttpServletRequest re,
			@RequestParam(required = false, value = "pageIndex") int pageIndex,
			@RequestParam(required = false, value = "pageSize") int pageSize,
			@RequestParam(required = false, value = "sortField") String sortField,
			@RequestParam(required = false, value = "sortOrder") String sortOrder)
			throws Exception {   
		List<Post> postList = null;
		Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
		PaginationVO page = new PaginationVO();
		page.setPageStart(pageIndex * pageSize);
		page.setPageIndex(pageIndex);
		page.setPageSize(pageSize);
		Post po = new Post();
		PostExample poe=new PostExample();
		if (key != null) {
			po.setPostUsername(key);
			poe.createCriteria().andPostUsernameLike("%"+key+"%");
		}
       page.setSortField(sortField);
       page.setSortOrder(sortOrder);
		postList = postServiceImpl.selectPageByAll(page, po);
		int total=postServiceImpl.countByExample(poe);		
		System.out.println("" + postList);
		page.setList(postList);
		page.setTotalField(total);	
		System.out.println(page);
		
		
		 rs.setContentType("application/json; charset=utf-8");
			PrintWriter  out = rs.getWriter();
			out.write( gson.toJson(page));
			out.flush();
			out.close();
		
		/*jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
				rs.getOutputStream());
		jsonGenerator.writeObject(page);*/
		

	}

	@RequestMapping(value = "/back")
	public String back() {
		return "back";

	}
	@RequestMapping(value = "/upload")
	public String upload() {
		return "upload";

	}
	
	/*@RequestMapping(value = "/form", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> form(@RequestParam("name") String name,@RequestParam("file")MultipartFile file,HttpServletRequest re) {
		Map<String, Object> map=new HashMap<String, Object>();
		if (file.isEmpty()) {
			map.put("msg", "文件未上传！");
		
		}else{
			System.out.println("文件的大小："+file.getSize());
			System.out.println("文件的类型："+file.getContentType());
			System.out.println("文件的原始名字："+file.getOriginalFilename());
			System.out.println("文件的名字："+file.getName());
			map.put("msg", "文件上传成功！");
			SimpleDateFormat f=new SimpleDateFormat("yyyyMMddHHmm");
		    
			String realpath=re.getSession().getServletContext().getRealPath("/static/upload");
			File f1=new File(realpath);
			if (!f1.exists()) {
				f1.mkdir();
			}
			
			String hzhui=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			String filename=+file.getOriginalFilename();
			System.out.println("我能得到的路径："+re.getSession().getServletContext().getRealPath("/static"));
			 try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realpath,f.format(new Date())+file.getOriginalFilename()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return map;

	}*/
	@RequestMapping(value = "/backlindex")
	public String backindex() {
		return "backindex";

	}
	@RequestMapping(value = "/new")
	public String mainBack() {
		return "New";

	}

	@RequestMapping(value = "/postInformation")
	public String postInformation() {
		return "postInformation";

	}

	@RequestMapping(value = "/add")
	public void add(@RequestParam("data") String data, HttpServletRequest rq,
			HttpServletResponse rs) {
		System.out.println("data=" + data);
		try {
			Post post = objectMapper.readValue(data, Post[].class)[0];
			System.out.println("_(_++()_+" + post);
			int flag = postServiceImpl.insert(post);
			rs.setCharacterEncoding("utf-8");
			rs.setContentType("text/html;charset=utf-8");
			jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
					rs.getOutputStream());
			jsonGenerator.writeObject(flag);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void saveData(@RequestParam("data") String data,
			HttpServletRequest rq, HttpServletResponse rs) {
		PostExample post = new PostExample();
		// JSONObject json=new JSONObject();
		Post article = new Post();
		System.out.println("____" + data);
		try {
			JsonParser jParser = objectMapper.getJsonFactory()
					.createJsonParser(data);
			// System.out.println(sp.getDoubleValue());
			if (jParser.nextToken() != JsonToken.END_OBJECT) {

				while (jParser.nextToken() != JsonToken.END_OBJECT) {

					String fieldname = jParser.getCurrentName();

					if ("postid".equals(fieldname)) {
						// 当前结点为name
						jParser.nextToken();
						article.setPostid(jParser.getIntValue());
						// System.out.println(); // 输出 mkyong

					}
					if ("userid".equals(fieldname)) {
						// 当前结点为name
						jParser.nextToken();

						article.setUserid(jParser.getIntValue());
						// System.out.println(jParser.getIntValue()); // 输出
						// mkyong

					}
					if ("postTitle".equals(fieldname)) {
						// 当前结点为name
						jParser.nextToken();
						article.setPostTitle(jParser.getText());
						// System.out.println(jParser.getText()); // 输出 mkyong

					}
					if ("postUsername".equals(fieldname)) {
						// 当前结点为name
						jParser.nextToken();
						article.setPostUsername(jParser.getText());
						// System.out.println(jParser.getText()); // 输出 mkyong

					}
					if ("postCreatetime".equals(fieldname)) {
						// 当前结点为name
						jParser.nextToken();
						String date = jParser.getText();
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyy-MM-dd kk:mm:ss.SSS");

						try {
							System.out.println("riqi===" + sdf.parse(date));
							article.setPostCreatetime(sdf.parse(date));
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// System.out.println(jParser.getText()); // 输出 mkyong

					}
					if ("postContent".equals(fieldname)) {
						// 当前结点为name
						jParser.nextToken();
						article.setPostContent(jParser.getText());
						// System.out.println(jParser.getText()); // 输出 mkyong

					}
					/*if ("postRead".equals(fieldname)) {
						// 当前结点为name
						jParser.nextToken();
						article.setPostRead(jParser.getIntValue());

					}*/
					if ("postResponse".equals(fieldname)) {
						// 当前结点为name
						jParser.nextToken();
						article.setPostResponse(jParser.getIntValue());

					}
				}
				System.out.println("+================" + article);
				int flag = postServiceImpl.updateByPrimaryKeySelective(article);
				System.out.println("flag==" + flag);
				rs.setCharacterEncoding("utf-8");
				rs.setContentType("text/html;charset=utf-8");
				jsonGenerator = objectMapper.getJsonFactory()
						.createJsonGenerator(rs.getOutputStream());
				jsonGenerator.writeObject(flag);

			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/query", method = RequestMethod.POST)
	public void query(@RequestParam("key") String key, HttpServletResponse rs)
			throws Exception {
		System.out.println("key=" + key);
		List<Post> articlelist = null;

		PaginationVO page = new PaginationVO();
		PostExample example = new PostExample();
		example.createCriteria().andPostUsernameLike(key);
		articlelist = postServiceImpl.selectByExample(example);
		System.out.println("^^^^^^^%%%%^^^^" + articlelist);
		page.setList(articlelist);
		page.setTotalField(articlelist.size());
		rs.setCharacterEncoding("utf-8");
		rs.setContentType("text/html;charset=utf-8");
		jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
				rs.getOutputStream());
		jsonGenerator.writeObject(page);

	}

	@RequestMapping(value = "/delete")
	public void deletedata(@RequestParam("id") String id, HttpServletResponse rs) {
		String[] arry = id.split(",");
		ArrayList<Integer> arryList = new ArrayList<Integer>();
		for (int i = 0; i < arry.length; i++) {
			arryList.add(Integer.parseInt(arry[i]));
		}
		System.out.println("+++++++++++++++++++++++" + arryList);
		PostExample example = new PostExample();
		example.createCriteria().andPostidIn(arryList);
		int flag = postServiceImpl.deleteByExample(example);
		rs.setCharacterEncoding("utf-8");
		rs.setContentType("text/html;charset=utf-8");
		try {
			jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
					rs.getOutputStream());
			jsonGenerator.writeObject(flag);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@RequestMapping(value="/findById")
	public void findById(@RequestParam("id") int id,HttpServletResponse rs){
		Post post=new Post();
		post= postServiceImpl.selectByPrimaryKey(id);
		//System.out.println("--findById----"+post);
		Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
		rs.setCharacterEncoding("utf-8");
		rs.setContentType("text/html;charset=utf-8");
		try {
			PrintWriter  out = rs.getWriter();
			out.write( gson.toJson(post));
			out.flush();
			out.close();
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@ResponseBody
	@RequestMapping(value="/test")
	public Map test(){
		//Gson g=new Gson();
		Map<String, Object> map=new HashMap<String, Object>();
		User user=new User();
		user.setUserid(1);
		user.setNickname("小明");
		user.setEmail("wqwewr@sina.com");
		user.setPassword("123456");
		user.setUsername("小明1");
		map.put("msg", "你好");
		map.put("user", user);
		return map;
		
	}
	@ResponseBody
	@RequestMapping(value="/test1")
	public User test11(){
	
		User user=new User();
		
		user.setUserid(39);
		User user1=new User();
		/*user1=impl.findrole(user);*/
		System.out.println("user1===="+user1);
		return user1;
		
	}
}
